package io;

import java.io.*;
import java.util.Scanner;



public class Demo13 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要搜索的路径: ");
        String path = scanner.next();

        System.out.println("请输入要查询的词: ");
        String searchWord = scanner.next();

        File rootFile = new File(path);
        if (!rootFile.isDirectory()) {
            System.out.println("当前输入的路径非法!");
            return;
        }
        search(rootFile,searchWord);
    }

    private static void search(File rootFile, String searchWord) {
        File[] files = rootFile.listFiles();
        if (files == null) {
            //空目录  结束
            return;
        }
        for (File f : files) {
            if (f.isFile()) {
                //文本文件  就读取文件内容并搜索
                matchWord(f,searchWord);
            }else if (f.isDirectory()) {
                //继续递归
                search(f,searchWord);
            }
        }
    }
    //负责对一个文本文件进行读取和判断
    private static void matchWord(File f, String searchWord) {
        try (Reader reader = new FileReader(f)){
            //把读到的结果最终构造到一个StringBuilder里面
            StringBuilder stringBuilder = new StringBuilder();
            while (true) {
                int c = reader.read();
                if (c == -1) {
                    break;
                }
                stringBuilder.append((char) c);
            }
            //循环结束  此时的文件所有的内容   就进入stringBuilder里面了
            if (stringBuilder.indexOf(searchWord) >= 0) {
                //找到了
                System.out.println("找到了匹配的结果 : " + f.getAbsolutePath());
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
